#ifndef _CLINE__
#define _CLINE__

#include <unistd.h>
#include <cstring>
#include <string>
#include <iostream>
#include "Log.hpp"
#include <cerrno>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Thread.hpp"
#include <memory>

int socket_;

void* send(void* args)
{
    struct sockaddr_in* goal_ = (sockaddr_in*)((ThreadDate*)args)->args; 
    std::string message;
    while (1)
    {
        std::cout<< "请输入发送信息#";
        std::getline(std::cin, message);
        // 回传套接字
        socklen_t len_goal = sizeof (*goal_);
        ssize_t st =  sendto(socket_, message.c_str(), message.size(), 0, (sockaddr*)goal_, len_goal);
        if (st < 0)
        {
            Logmessage(WAIN, "sendto %d : %s\n", errno, strerror(errno));
        }
    }
    return nullptr;
}

void* reception(void* args)
{
    char buff[1024];
    while (1)
    {
        struct sockaddr_in tmp;
        bzero(&tmp, sizeof tmp);
        socklen_t len = sizeof tmp;
        ssize_t ret = recvfrom(socket_, buff, (sizeof buff) - 1, 0, (sockaddr*)&tmp, &len);
        if (ret > 0)
        {
            buff[ret] = 0;
            std::cout << buff << std::endl;
        }
    }   
    return nullptr;
}

int main(int argc, char* args[])
{
    if (argc != 3)
    {
        [args]{printf("%s需要id,port参数\n", args[0]);}();
        exit(1);
    }
    socket_ = socket(AF_INET, SOCK_DGRAM, 0);
    if ( socket_ < 0)
    {
        Logmessage(FATIL, "socker creat %d:%s\n", errno, strerror(errno));
        exit(1);
    }

    struct sockaddr_in goal_;
    bzero(&goal_, sizeof goal_);
    goal_.sin_family = AF_INET;
    goal_.sin_addr.s_addr = inet_addr(args[1]);
    goal_.sin_port = htons(atoi(args[2]));

    std::unique_ptr<Thread> send_server (new Thread(1, send, (void*)&goal_));
    std::unique_ptr<Thread> reception_server (new Thread(2, reception, nullptr));
    send_server->start();
    reception_server->start();

    send_server->join();
    reception_server->join();


    close(socket_);
    // // 在客户端不用bind ip与端口号，因为：
    // // 服务器是提供服务的，就那几台，而客户端有未知个，未知的ip,端口占用情况
    // // 在sendto时，OS会自动创建IP与端口号
    // std::string message;
    // char buff[1024];
    // while (1)
    // {
    //     std::cout<< "请输入发送信息#";
    //     std::getline(std::cin, message);
    //     // 回传套接字
    //     socklen_t len_goal = sizeof goal_;
    //     ssize_t st =  sendto(socket_, message.c_str(), message.size(), 0, (sockaddr*)&goal_, len_goal);
    //     if (st < 0)
    //     {
    //         Logmessage(NOWAIN, "sendto %n : %s\n", errno, strerror(errno));
    //     }

    //     struct sockaddr_in tmp;
    //     bzero(&tmp, sizeof tmp);
    //     socklen_t len = sizeof tmp;
    //     ssize_t ret = recvfrom(socket_, buff, (sizeof buff) - 1, 0, (sockaddr*)&tmp, &len);
    //     if (ret > 0)
    //     {
    //         buff[ret] = 0;
    //         std::cout << buff << std::endl;
    //     }
    // }   
    // close(socket_);
}

#endif






